package com.schoolgard.action.upgrade;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import com.schoolegard.services.DeviceService;
import com.schoolegard.services.UpgradeToDeviceService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.common.FtpConstants;
import com.schoolgard.entitybean.Device;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.JobMode;
import com.schoolgard.entitybean.JobStatus;
import com.schoolgard.entitybean.UpgradeToDevice;
import com.schoolgard.entitybean.Users;
import com.supersystem.utils.DateJsonValueProcessor;
import com.supersystem.utils.DateUtil;

public class UpgradeAction extends BaseAction {

	private static Logger logger = Logger.getLogger(UpgradeAction.class);
	private static final long serialVersionUID = 201112052117L;

	private UpgradeToDeviceService upgradeToDeviceService;
	private DeviceService deviceService;
	private UpgradeToDevice uptd;
	
	

	public void findAllJobs() {
		String startStr = request.getParameter("start"); // grid传过来的当前数据条数
		String limitStr = request.getParameter("limit"); // 每页显示的数据数

		int start = Integer
				.parseInt(StringUtils.isNotBlank(startStr) ? startStr : "0");
		int limit = Integer
				.parseInt(StringUtils.isNotBlank(limitStr) ? limitStr : "30");
		int end = start + limit; // 当前页需要显示的数据 start--> end
		List<UpgradeToDevice> jobs = upgradeToDeviceService.findAll();
		int total = jobs.size();
		if (end > total)
			end = total;

		JsonValueProcessor jsonProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, jsonProcessor);

		GridDataModel<UpgradeToDevice> page = new GridDataModel<UpgradeToDevice>();
		page.setPage(start / limit + 1);
		page.setRows(jobs);
		page.setTotal(total);
		String jsonStr = JSONObject.fromObject(page, config).toString();
		writeToResponse(jsonStr);
	}

	public void saveJobs() {
		String jobModeId = request.getParameter("jobModeId");
		String guid = uptd.getGuid();
		if (StringUtils.isNotBlank(guid)) {
			List<Device> devices = deviceService.findByAnyId(guid);
			List<UpgradeToDevice> utds = new ArrayList<UpgradeToDevice>();
			for(Device device : devices){
				UpgradeToDevice job = new UpgradeToDevice();
				job.setRouter(deviceService.findRouter(device));
				job.setObjectName(device.getName());
				job.setCreateDatetime(new Date());
				job.setEnable(uptd.getEnable());
				job.setFileName(uptd.getFileName());
				job.setNewVersion(uptd.getNewVersion());
				job.setOldVersion(uptd.getOldVersion());
				job.setStartDownloadDatetime(uptd.getStartDownloadDatetime());
				if (guid.indexOf("de_") != -1) {
					job.setType(1); // 服务器
					guid = guid.replace("de_", "");
				} else if (guid.indexOf("te_") != -1) {
					job.setType(2); // 终端
					guid = guid.replace("te_", "");
				}
				job.setGuid(device.getGuid());
				job.setJobMode(upgradeToDeviceService.findJobModeById(StringUtils
						.isNotBlank(jobModeId) ? Long.valueOf(jobModeId) : 0));
				job.setJobStatus(upgradeToDeviceService.findjobStatusById(100L));
				Users user = (Users) session.get("user");
				if (user != null) {
					job.setUserId(user.getId());
					job.setUserName(user.getName());
				}
				utds.add(job);
			}
			try {
				upgradeToDeviceService.saveAll(utds);
				writeToResponse("1");
			} catch (Exception e) {
				e.printStackTrace();
				writeToResponse("0");
			}
		}
	}

	public void findJobStatus() {
		List<JobStatus> ls = upgradeToDeviceService.findJobStatus();
		JSONArray result = new JSONArray();
		for (JobStatus jobStatus : ls) {
			result.add(buildCombo(jobStatus.getId().toString(),
					jobStatus.getName()));
		}
		writeToResponse(result.toString());
	}

	public void findJobMode() {
		List<JobMode> ls = upgradeToDeviceService.findJobMode();
		JSONArray result = new JSONArray();
		for (JobMode jobMode : ls) {
			result.add(buildCombo(jobMode.getId().toString(), jobMode.getName()));
		}
		writeToResponse(result.toString());
	}

	public void deleteJob() {
		String jobId = request.getParameter("jobId");
		if (StringUtils.isBlank(jobId))
			return;
		try {
			upgradeToDeviceService.delete(Long.valueOf(jobId));
			writeToResponse("1");
		} catch (Exception e) {
			e.printStackTrace();
			writeToResponse("0");
		}
	}

	public void findFiles() {
		try {
			FTPClient ftp = new FTPClient();
			int reply;
			ftp.connect(FtpConstants.ADDRESS, FtpConstants.PORT);
			ftp.login(FtpConstants.USER_NAME, FtpConstants.PASSWORD);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return ;
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			ftp.changeWorkingDirectory(FtpConstants.PATH);
			FTPFile[] files = ftp.listFiles();
			List<JSONObject> list = new ArrayList<JSONObject>();
			for(FTPFile file : files) {
				if(file.isDirectory()){
					continue;
				}
				JSONObject result = new JSONObject();
				result.put("name", file.getName());
				result.put("size", file.getSize());
				result.put("date", DateUtil.formatTime(file.getTimestamp().getTime()));
				result.put("path", FtpConstants.PATH+"/"+file.getName());
				list.add(result);
			}
			ftp.logout();
			int start = 0;
			int limit = list.size();
			GridDataModel<JSONObject> page = new GridDataModel<JSONObject>();
			int total = list.size();
			page.setPage(start / limit + 1);
			page.setRows(list);
			page.setTotal(total);
			String jsonStr = JSONObject.fromObject(page).toString();
			writeToResponse(jsonStr);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 封装combo数据
	 * 
	 * @param id
	 * @param name
	 * @return
	 */
	private JSONObject buildCombo(String id, String name) {
		JSONObject result = new JSONObject();
		result.put("value", id);
		result.put("text", name);
		return result;
	}

	public UpgradeToDevice getUptd() {
		return uptd;
	}

	public void setUptd(UpgradeToDevice uptd) {
		this.uptd = uptd;
	}

	public void setUpgradeToDeviceService(
			UpgradeToDeviceService upgradeToDeviceService) {
		this.upgradeToDeviceService = upgradeToDeviceService;
	}

	public void setDeviceService(DeviceService deviceService) {
		this.deviceService = deviceService;
	}
	
}
